import Access from '@/components/Access';
import type { ProColumns } from '@/components/Pro';
import { ProTable } from '@/components/Pro';
import { upgradeManageControllerList } from '@/services/ess/upgradeManage';
import { DATABASE_TYPE_ENUM, fetchDictInfo } from '@/utils';
import { useModel } from '@@/exports';
import dayjs from 'dayjs';
import React, { useEffect, useState } from 'react';
import { Link, useIntl } from 'umi';
import Styles from '../index.less';

const UpgradeManagement: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const [tenantOptions, setTenantOptions] = useState([]);
  const [deviceOptions, setDeviceOptions] = useState([]);
  const intl = useIntl();
  const isEnglish = intl.locale === 'en-US';
  const tableColumns: ProColumns[] = [
    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.generalProcedure.SN' }),
      dataIndex: 'NO',
      key: 'NO',
      valueType: 'index',
      width: 60,
    },
    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.versionManagement.upgradePackage' }),
      dataIndex: 'packageName',
      hideInSearch: true,
      width: 180,
      render: (_, record) => {
        return <span>{record?.record?.packageName}</span>;
      },
    },
    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.upgradeManagement.edition' }),
      dataIndex: 'version',

      hideInSearch: true,
      render: (_, record) => {
        return <span>{record?.record?.version}</span>;
      },
    },
    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.upgradeManagement.upgradeStatus' }),
      dataIndex: 'upgradeStatus',
      initialValue: '',
      key: 'upgradeStatus',
      valueType: 'select',
      request: async () => {
        return [
          {
            label: intl.formatMessage({ id: 'remoteUpgradeMangment.generalProcedure.all' }),
            value: '',
          },
          ...(await fetchDictInfo(DATABASE_TYPE_ENUM.UPDATE_STATUS)),
        ];
      },
    },
    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.upgradeManagement.tenantName' }),
      dataIndex: 'tenantName',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.upgradeManagement.plantName' }),
      dataIndex: 'stationName',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.versionManagement.deviceType' }),
      dataIndex: 'deviceType',
      key: 'deviceType',
      valueType: 'select',
      request: async () => {
        return await fetchDictInfo(DATABASE_TYPE_ENUM.UPDATE_DEVICE_TYPE);
      },
      render: (_, record) => {
        return (
          <span>
            {
              deviceOptions?.filter((item) => {
                return item.value === record?.record?.deviceType;
              })[0]?.label
            }
          </span>
        );
      },
    },
    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.versionManagement.deviceModel' }),
      dataIndex: 'deviceModel',
      key: 'deviceModel',
      render: (_, record) => {
        return <span>{record?.record?.deviceModel}</span>;
      },
    },
    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.upgradeManagement.deviceName' }),
      dataIndex: 'deviceName',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.upgradeManagement.tenantPlant' }),
      dataIndex: 'tenantOrStation',
      key: 'tenantOrStation',
      valueType: 'cascader',
      hideInTable: true,
      fieldProps: {
        options: tenantOptions,
        changeOnSelect: true,
      },
      search: {
        transform: (value) => {
          return {
            tenantOrStation: value.at(-1),
          };
        },
      },
    },

    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.upgradeManagement.upgradeTime' }),
      dataIndex: 'upgradeTime',
      key: 'upgradeTime',
      width: 150,
      initialValue: [dayjs().subtract(6, 'day'), dayjs()],
      valueType: 'dateRange',
      render: (_, record) => {
        return <span>{record.createTime}</span>;
      },
      search: {
        transform: (value) => {
          return {
            upgradeStartTime: value[0],
            upgradeEndTime: value[1],
          };
        },
      },
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.generalProcedure.operation' }),
      hideInSearch: true,
      dataIndex: 'operation',
      key: 'operation',
      render: (_, record) => {
        return (
          <>
            <Access perm={'remote:ota:view'} key={'link'}>
              <Link
                to={`/remoteUpgrade/upgradeManagement/detail?id=${record?.flowId}`}
                key={'link'}
              >
                <span>
                  {intl.formatMessage({ id: 'remoteUpgradeMangment.generalProcedure.detail' })}
                </span>
              </Link>
            </Access>
          </>
        );
      },
    },
  ];
  const getTenantOptions = (options: any) => {
    const treeData = [];

    function getTreeChildren(stationOptions: any[]) {
      return stationOptions.map((item) => {
        return {
          label: item.stationName,
          value: item.stationName,
        };
      });
    }

    options.forEach((item) => {
      treeData.push({
        value: item.tenantName,
        label: item.tenantName,
        children: getTreeChildren(item.stationInfos),
      });
    });

    setTenantOptions(treeData);
  };

  useEffect(() => {
    getTenantOptions(initialState?.tenants);
    fetchDictInfo(100009).then((res) => {
      setDeviceOptions(res);
    });
  }, []);
  return (
    <>
      <ProTable
        rowKey={'pageIndex'}
        headerTitle={
          <div className={`${isEnglish ? Styles.table_header_title : ''}`}>
            {intl.formatMessage({
              id: 'remoteUpgradeMangment.upgradeManagement.upgradeManagement',
            })}
          </div>
        }
        columns={tableColumns}
        request={upgradeManageControllerList}
      ></ProTable>
    </>
  );
};

export default UpgradeManagement;
